<?php
declare(strict_types=1);

namespace app\controller\merchant;

use app\controller\BaseController;
use app\model\{WorkChatRecord, WorkChatMember, MerchantApplication};
use app\service\WechatService;
use think\facade\{Cache, Log};

class WorkChatController extends BaseController
{
    /**
     * 获取群聊列表
     */
    public function list()
    {
        $page = input('page/d', 1);
        $limit = input('limit/d', 10);
        $status = input('status/d', 0);
        
        $where = [
            'merchant_id' => request()->merchant_id
        ];
        if ($status) {
            $where['status'] = $status;
        }
        
        $list = WorkChatRecord::where($where)
            ->with(['members'])
            ->order('create_time', 'desc')
            ->page($page, $limit)
            ->select();
            
        $total = WorkChatRecord::where($where)->count();
        
        return json([
            'code' => 0,
            'msg' => 'success',
            'data' => [
                'list' => $list,
                'total' => $total,
                'page' => $page,
                'limit' => $limit
            ]
        ]);
    }
    
    /**
     * 获取群成员列表
     */
    public function members()
    {
        $chatId = input('chat_id/s', '');
        $page = input('page/d', 1);
        $limit = input('limit/d', 10);
        
        if (empty($chatId)) {
            return json(['code' => 1, 'msg' => '群聊ID不能为空']);
        }
        
        // 验证群聊是否属于当前商家
        $chat = WorkChatRecord::where([
            'merchant_id' => request()->merchant_id,
            'chat_id' => $chatId
        ])->find();
        
        if (!$chat) {
            return json(['code' => 1, 'msg' => '群聊不存在']);
        }
        
        // 获取群成员列表
        $list = WorkChatMember::alias('m')
            ->join('user u', 'u.work_userid = m.userid', 'LEFT')
            ->where('m.chat_id', $chatId)
            ->field([
                'm.*',
                'u.real_name',
                'u.work_name',
                'u.work_avatar',
                'u.work_mobile'
            ])
            ->order('m.join_time', 'desc')
            ->page($page, $limit)
            ->select();
            
        $total = WorkChatMember::where('chat_id', $chatId)->count();
        
        return json([
            'code' => 0,
            'msg' => 'success',
            'data' => [
                'list' => $list,
                'total' => $total,
                'page' => $page,
                'limit' => $limit
            ]
        ]);
    }
    
    /**
     * 解散群聊
     */
    public function dismiss()
    {
        $chatId = input('chat_id/s', '');
        
        if (empty($chatId)) {
            return json(['code' => 1, 'msg' => '群聊ID不能为空']);
        }
        
        // 验证群聊是否属于当前商家
        $chat = WorkChatRecord::where([
            'merchant_id' => request()->merchant_id,
            'chat_id' => $chatId
        ])->find();
        
        if (!$chat) {
            return json(['code' => 1, 'msg' => '群聊不存在']);
        }
        
        // 获取企业微信配置
        $merchant = MerchantApplication::where('merchant_id', request()->merchant_id)
            ->where('application_type', 4)
            ->find();
            
        if (!$merchant) {
            return json(['code' => 1, 'msg' => '请先配置企业微信']);
        }
        
        $config = [
            'corp_id' => $merchant->app_id,
            'secret' => $merchant->app_secret
        ];
        
        // 调用企业微信API解散群聊
        $result = (new WechatService())->dismissWorkChat($config, $chatId);
        
        if ($result === false) {
            return json(['code' => 1, 'msg' => '解散群聊失败']);
        }
        
        // 更新群聊状态
        $chat->status = 2;
        $chat->save();
        
        // 更新群成员状态
        WorkChatMember::where('chat_id', $chatId)
            ->update(['status' => 2]);
        
        return json(['code' => 0, 'msg' => '解散成功']);
    }
    
    /**
     * 获取群聊统计数据
     */
    public function statistics()
    {
        $merchantId = request()->merchant_id;
        
        // 总群聊数
        $totalChats = WorkChatRecord::where('merchant_id', $merchantId)->count();
        
        // 活跃群聊数
        $activeChats = WorkChatRecord::where([
            'merchant_id' => $merchantId,
            'status' => 1
        ])->count();
        
        // 总成员数
        $totalMembers = WorkChatMember::alias('m')
            ->join('work_chat_record r', 'r.chat_id = m.chat_id')
            ->where([
                'r.merchant_id' => $merchantId,
                'm.status' => 1
            ])->count();
            
        // 今日新增成员数
        $todayMembers = WorkChatMember::alias('m')
            ->join('work_chat_record r', 'r.chat_id = m.chat_id')
            ->where([
                'r.merchant_id' => $merchantId,
                'm.status' => 1
            ])
            ->whereDay('m.create_time')
            ->count();
        
        return json([
            'code' => 0,
            'msg' => 'success',
            'data' => [
                'total_chats' => $totalChats,
                'active_chats' => $activeChats,
                'total_members' => $totalMembers,
                'today_members' => $todayMembers
            ]
        ]);
    }
    
    /**
     * 获取入群二维码
     */
    public function getJoinQrcode()
    {
        $params = $this->request->post();
        
        // 参数验证
        $validate = validate([
            'chat_id_list' => 'array',
            'remark' => 'max:30',
            'room_base_name' => 'max:30',
            'auto_create_room' => 'in:0,1'
        ]);
        
        if (!$validate->check($params)) {
            return json(['code' => 1, 'msg' => $validate->getError()]);
        }
        
        // 获取商家的企业微信配置
        $merchant = MerchantApplication::where('merchant_id', $this->merchantId)
            ->where('application_type', 4) // 企业微信通讯录
            ->find();
            
        if (!$merchant) {
            return json(['code' => 1, 'msg' => '请先配置企业微信']);
        }
        
        $config = [
            'corp_id' => $merchant->app_id,
            'secret' => $merchant->app_secret
        ];
        
        $result = (new WechatService())->getJoinQrcode($config, $params);
        
        if ($result === false) {
            return json(['code' => 1, 'msg' => '获取二维码失败']);
        }
        
        return json([
            'code' => 0,
            'msg' => 'success',
            'data' => [
                'config_id' => $result['config_id'],
                'qr_code' => $result['qr_code']
            ]
        ]);
    }
} 